package cn.getech.data.development.service.impl;


import cn.getech.data.development.constant.DataDevelopmentBizExceptionEnum;
import cn.getech.data.development.constant.RangerMaskType;
import cn.getech.data.development.entity.*;
import cn.getech.data.development.mapper.*;
import cn.getech.data.development.model.dto.TableFieldInfoDto;
import cn.getech.data.development.model.dto.TableFieldMaskRulesDto;
import cn.getech.data.development.model.dto.TableInfoDto;
import cn.getech.data.development.service.ITableFieldMaskRulesService;
import cn.getech.data.intelligence.common.exception.RRException;
import cn.getech.data.intelligence.common.utils.PojoUtils;
import cn.getech.system.center.utils.ShiroUtils;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hujz
 * @since 2020-02-19
 */
@Service
public class TableFieldMaskRulesServiceImpl extends ServiceImpl<TableFieldMaskRulesMapper, TableFieldMaskRules> implements ITableFieldMaskRulesService {

    @Autowired
    private TableFieldInfoMapper tableFieldInfoMapper;

    @Autowired
    private TableFieldMaskRulesMapper tableFieldMaskRulesMapper;

    @Autowired
    private TableInfoMapper tableInfoMapper;

    @Autowired
    private DataPermissionParamMapper dataPermissionParamMapper;

    @Autowired
    private CusMaskUdfMapper cusMaskUdfMapper;

    @Override
    public List<TableFieldInfoDto> listNotDataMaskingField(Integer id) {
        //查询到所有的表的字段
        List<TableFieldInfo> tableFieldInfos = tableFieldInfoMapper.selectList(new QueryWrapper<TableFieldInfo>().eq("table_id", id));
        if(CollectionUtil.isEmpty(tableFieldInfos)){
            return null;
        }
        //数据脱敏配置接口合并，库表字段直接返回
        return PojoUtils.listConvert(TableFieldInfoDto.class,tableFieldInfos);
//        //查询到配置的规则信息
//        List<TableFieldMaskRules> tableFieldMaskRules = tableFieldMaskRulesMapper.selectList(new QueryWrapper<TableFieldMaskRules>().eq("table_id", id));
//        if(CollectionUtil.isEmpty(tableFieldMaskRules)){
//            return PojoUtils.listConvert(TableFieldInfoDto.class,tableFieldInfos);
//        }
//        //挑选出其中未配置的字段
//        List<Integer> tableFieldIds = new ArrayList<>();
//        tableFieldMaskRules.forEach(tableFieldMaskRules1 -> {
//            tableFieldIds.add(tableFieldMaskRules1.getTableFieldId());
//        });
//
//        List<TableFieldInfoDto> restList = new ArrayList<>();
//        //拼装成对应的数据返回
//        tableFieldInfos.forEach(tableFieldInfo -> {
//            if(!tableFieldIds.contains(tableFieldInfo.getId())){
//                TableFieldInfoDto tableFieldInfoDto = new TableFieldInfoDto();
//                BeanUtils.copyProperties(tableFieldInfo,tableFieldInfoDto);
//                restList.add(tableFieldInfoDto);
//            }
//        });
//        return restList;
    }

    @Override
    public TableInfoDto getByTableId(Integer id) {

        TableInfo tableInfo = tableInfoMapper.selectById(id);
        if(null == tableInfo){
            return null;
        }
        TableInfoDto tableInfoDto = new TableInfoDto();
        BeanUtils.copyProperties(tableInfo,tableInfoDto);
        return tableInfoDto;
    }

    @Override
    public List<TableFieldMaskRulesDto> listDataMaskingField(Integer id,Integer tenantId) {
        //查询到所有的配置这个行规则信息并且返回
        List<TableFieldMaskRulesDto> restList = tableFieldMaskRulesMapper.selectByTableId(id,tenantId);
        return restList;
    }

    @Override
    public void deleteById(Integer id) {
        tableFieldMaskRulesMapper.deleteById(id);
    }

    @Override
    public void saveTableMaskOpen(TableInfoDto tableInfoDto) {
        //验证白名单
        /*if(StringUtils.isNotEmpty(tableInfoDto.getTableMaskWhiteList())){
            List<DataPermissionParam> dataPermissionParams = dataPermissionParamMapper.selectList(new QueryWrapper<DataPermissionParam>().eq("permiss_type", 1));
            if(CollectionUtil.isEmpty(dataPermissionParams)){
                return;
            }
            List<String> tableLevelIds = new ArrayList<>();
            dataPermissionParams.forEach(dataPermissionParam -> {
                tableLevelIds.add(dataPermissionParam.getId().toString());
            });
            String[] split = tableInfoDto.getTableMaskWhiteList().split(",");
            for (String s : split) {
                if(!tableLevelIds.contains(s)){
                    throw new RRException(DataDevelopmentBizExceptionEnum.TABLE_LEVEL_ID_NOT_FOUND.getMessage());
                }
            }
        } else {
            if(null == tableInfoDto.getTableMaskWhiteList()){
                tableInfoDto.setTableMaskWhiteList("");
            }
        }*/
        //进行保存操作
        TableInfo tableInfo = tableInfoMapper.selectById(tableInfoDto.getId());
        if(null == tableInfo){
            throw new RRException(DataDevelopmentBizExceptionEnum.TABLE_NOT_EXIST.getMessage());
        }
        tableInfo.setTableMaskOpen(tableInfoDto.getTableMaskOpen());
        if (StringUtils.isEmpty(tableInfoDto.getTableMaskWhiteList())) {
            tableInfo.setTableMaskWhiteList("");
        }else{
            tableInfo.setTableMaskWhiteList(tableInfoDto.getTableMaskWhiteList());
        }
        tableInfo.setTenantId(ShiroUtils.getTenantId());
        tableInfoMapper.updateById(tableInfo);
    }

    @Override
    public TableFieldMaskRules saveTableFieldRules(TableFieldMaskRulesDto tableFieldMaskRulesDto) {
        //查询到所有的规则数据
        cheackFieldIsHave(tableFieldMaskRulesDto.getTableFieldId(),null);
        //查看这个代码验证情况
        TableFieldInfo tableFieldInfo = tableFieldInfoMapper.selectById(tableFieldMaskRulesDto.getTableFieldId());
        if(null == tableFieldInfo){
            throw new RRException(DataDevelopmentBizExceptionEnum.TABLE_FIELD_NOT_FOUND.getMessage());
        }
        //验证一下规则，是否正确
        cheackMaskTypeAndValue(tableFieldMaskRulesDto.getMaskType(),tableFieldMaskRulesDto.getMaskValue());

        TableFieldMaskRules tableFieldMaskRules = new TableFieldMaskRules();
        tableFieldMaskRules.setTableId(tableFieldInfo.getTableId());
        tableFieldMaskRules.setTableFieldId(tableFieldInfo.getId());
        tableFieldMaskRules.setMaskType(tableFieldMaskRulesDto.getMaskType());
        tableFieldMaskRules.setMaskValue(tableFieldMaskRulesDto.getMaskValue());
        tableFieldMaskRulesMapper.insert(tableFieldMaskRules);
        return tableFieldMaskRules;
    }

    private void cheackMaskTypeAndValue(Integer maskType, String maskValue) {
        if(maskType >= RangerMaskType.MASK_CUSTOM.getId()){
            //还得验证对应的udf是否注册过，没有成功注册过，则不能让其保存
            CusMaskUdf cusMaskUdf = cusMaskUdfMapper.selectById(maskType);
            if(null == cusMaskUdf || 0 == cusMaskUdf.getIsReginster()){
                throw new RRException(DataDevelopmentBizExceptionEnum.PARAM_ERROR_INNER_UDF.getMessage());
            }
            if(8 == maskType || 9 == maskType){
                if(StringUtils.isEmpty(maskValue)){
                    throw new RRException(DataDevelopmentBizExceptionEnum.PARAM_ERROR_VALUE.getMessage());
                }
                String[] split = maskValue.split(",");
                if(null == split || split.length < 2){
                    throw new RRException(DataDevelopmentBizExceptionEnum.PARAM_ERROR_VALUE.getMessage());
                }
                Integer start;
                Integer end;
                try {
                    start = Integer.valueOf(split[0]);
                    end = Integer.valueOf(split[1]);
                } catch (Exception e){
                    throw new RRException(DataDevelopmentBizExceptionEnum.PARAM_ERROR_VALUE_NUMBER.getMessage());
                }
                if(end < start){
                    throw new RRException(DataDevelopmentBizExceptionEnum.PARAM_ERROR_START_END.getMessage());
                }
            }
        }
    }

    @Override
    public void updateTableFieldRules(TableFieldMaskRulesDto tableFieldMaskRulesDto) {
        //检验字段的重复性
        cheackFieldIsHave(tableFieldMaskRulesDto.getTableFieldId(),tableFieldMaskRulesDto.getId());
        //查看这个代码验证情况
        TableFieldInfo tableFieldInfo = tableFieldInfoMapper.selectById(tableFieldMaskRulesDto.getTableFieldId());
        if(null == tableFieldInfo){
            throw new RRException(DataDevelopmentBizExceptionEnum.TABLE_FIELD_NOT_FOUND.getMessage());
        }
        TableFieldMaskRules tableFieldMaskRules = tableFieldMaskRulesMapper.selectById(tableFieldMaskRulesDto.getId());
        if(null == tableFieldMaskRules){
            throw new RRException(DataDevelopmentBizExceptionEnum.TABLE_MASK_NOT_FOUND.getMessage());
        }
        //验证字段是否改变
        if(!Objects.equals(tableFieldMaskRules.getTableFieldId(),tableFieldInfo.getId())){
            throw new RRException(DataDevelopmentBizExceptionEnum.TABLE_MASK_RILES_UPDATE_ERROR.getMessage());
        }
        //验证一下规则，是否正确
        cheackMaskTypeAndValue(tableFieldMaskRulesDto.getMaskType(),tableFieldMaskRulesDto.getMaskValue());
        //修改
        tableFieldMaskRules.setMaskType(tableFieldMaskRulesDto.getMaskType());
        tableFieldMaskRules.setMaskValue(tableFieldMaskRulesDto.getMaskValue());
        tableFieldMaskRules.setTableFieldId(tableFieldInfo.getId());
        tableFieldMaskRules.setTableId(tableFieldInfo.getTableId());
        tableFieldMaskRulesMapper.updateById(tableFieldMaskRules);
    }

    private void cheackFieldIsHave(Integer tableFieldId,Integer id) {
        //查询这个字段是否配置过
        List<TableFieldMaskRules> tableFieldMaskRules = tableFieldMaskRulesMapper.selectList(
                new QueryWrapper<TableFieldMaskRules>()
                        .eq("table_field_id", tableFieldId)
                        .ne(null != id,"id",id));
        if(CollectionUtil.isNotEmpty(tableFieldMaskRules)){
            throw new RRException(DataDevelopmentBizExceptionEnum.TABLE_FIELD_MASK_RULES_HAVE_FOUND.getMessage());
        }
    }
}
